//
//  TokenManager.swift
//  osc
//
//  Created by admin on 14/11/3.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import Foundation
import UIKit
import CoreData

class TokenManager {

    
    
    
    class func addToken(tokenM: TokenM){
        var entityName = NSStringFromClass(Tokencc.classForCoder())
        
        var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var managedObjectContext = appDelegate.managedObjectContext!
        
        var token = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext ) as  Tokencc
        
        
        token.access_token = tokenM.access_token!
        token.refresh_token = tokenM.refresh_token!
        token.token_type = tokenM.token_type!
        token.expires_in = tokenM.expires_in!
        token.uid = tokenM.uid!
        //token.is_online = tokenM.is_online
        
        var savingError: NSError?
        
        if managedObjectContext.save(&savingError){
            println("Successfully saved the new Token")
        } else {
            if let error = savingError{
                println("Failed to save the new Token. Error = \(error)")
            }
        }
        listToken()
    }
    
    class func listToken()->String{
        
        var token = ""
        var entityName = NSStringFromClass(Tokencc.classForCoder())
        
        var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var managedObjectContext = appDelegate.managedObjectContext!
        
        var fetchRequest : NSFetchRequest = NSFetchRequest(entityName: entityName)
        
        var error: NSError?
        
        var tokens = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [Tokencc!]
        
        
        /* Make sure we get the array */
        if tokens.count > 0{
            
            var counter = 1
            for token in tokens{
                
                println("token \(counter) token.access_token = \(token.access_token)")
                println("token \(counter) refresh_token = \(token.refresh_token)")
                println("token \(counter) token.token_type = \(token.token_type)")
                println("token \(counter) token.expires_in = \(token.expires_in)")
                println("token \(counter) token.uid = \(token.uid)")
                
                counter++
            }
            token = tokens[0].access_token as String

            
        } else {
            println("Could not find any Person entities in the context")
            token = ""
        }
        
        return token
    }
}